package metamapp

import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import util.ValidateUtil
import util.StatisticsAttributesUtil
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.apache.log4j.Logger
import util.FileUtility

class StatisticsAttributesController {

    Logger gLogger = Logger.getLogger(StatisticsAttributesController.class)

    def index = {

      // MultipartHttpServletRequest is used to read attached files
      if(request instanceof MultipartHttpServletRequest){
          MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;

          def ActionVal = mpr.getAttribute("ActionVal")

          if( ActionVal ==null || !ActionVal.toString().equalsIgnoreCase("Download")){

             boolean isValidate = true
             flash.message = ""
             gLogger.info "============ Comming into submit mathod of StatisticsAttributesController ================\n"
             gLogger.info "parmas.txtNoCon :: ${params.txtNoCon}"
             gLogger.info "parmas.txtThreshold :: ${params.txtThreshold}"
             gLogger.info "parmas.fileStatistics :: ${params.fileStatistics}"
             gLogger.info "parmas.fileStatistics.getClass :: ${params.fileStatistics?.getClass()}"

             CommonsMultipartFile fileStatistics = (CommonsMultipartFile) mpr.getFile("fileStatistics");

             if( params.txtNoCon == null || params.txtNoCon.toString().trim().length() == 0 ){
                isValidate = false
                flash.message = "Error! Number of condition is mandatory."
                redirect(action:"index",params:params)               
             }else if( !ValidateUtil.getInstance().isInteger(params.txtNoCon.toString()) ){
                isValidate = false
                flash.message = "Error! Number of condition should be an integer"
                redirect(action:"index",params:params)
             }else if( params.txtThreshold == null || params.txtThreshold.toString().trim().length() == 0 ){
                isValidate = false
                flash.message = "Error! P Value Threshold is mandatory."
                redirect(action:"index",params:params)
             }else if( params.txtThreshold == null || !ValidateUtil.getInstance().isDouble(params.txtThreshold.toString()) ){
                isValidate = false
                flash.message = "Error! P Value Threshold should be a decimal number"
                redirect(action:"index",params:params)
             }else if( Double.parseDouble(params.txtThreshold) < 0.01 || Double.parseDouble(params.txtThreshold) >= 1.0 ){
                isValidate = false
                flash.message = "Error! Please enter P Value Threshold between the range of 0.01 to 1.0"
                redirect(action:"index",params:params)
             }else if( fileStatistics.empty )
             {
                isValidate = false
                flash.message = "Error! Statistical data file is mandatory."
                redirect(action:"index",params:params)
             }else if( !fileStatistics.contentType.toString().equalsIgnoreCase("text/plain") && !fileStatistics.contentType.toString().equalsIgnoreCase("text/csv") &&
                     !fileStatistics.contentType.toString().equalsIgnoreCase("application/vnd.ms-excel") && !fileStatistics.contentType.toString().equalsIgnoreCase("application/save-to-disk"))
             {
                isValidate = false
                flash.message = "Error! Statistical data file has bad extension (contentType : ${fileStatistics.contentType}) , Upload only .csv or .txt extension file."
                redirect(action:"index",params:params)
             }


             if(isValidate){
               String statisticsData = "";
               // read attached file and prepare string out of it
               if(!fileStatistics.empty)
               {
                 Reader reader = new InputStreamReader(fileStatistics.getInputStream());
                 statisticsData = FileUtility.getInstance().readFileStreamAsString(reader);
               }

               // Calculate Statistics Attributes
               ArrayList<String> attributeList = StatisticsAttributesUtil.getInstance().processStatisticsAttributes(statisticsData,Long.parseLong(params.txtNoCon.toString()),Double.parseDouble(params.txtThreshold.toString()));
               session.setAttribute "attributeList",attributeList
               session.setAttribute "totalConditions",params.txtNoCon

               def fileName = fileStatistics?.getOriginalFilename()

               // if file name is not there, give it to a default name
               if(fileName == null || fileName.trim().length() == 0 ){
                  fileName = "default"
               }

               // remove extension of the file
               if(fileName.toString().lastIndexOf(".") != -1){
                  fileName = fileName.toString().substring(0, fileName.toString().lastIndexOf("."))
               }

               // remove spaces from the filename if there any
               fileName = fileName.replaceAll(" ","_");

               boolean isNodeAttribute = true;

               return ["isNodeAttribute":isNodeAttribute,"fileName":fileName]
             }
          }
      }else{
            // prepare result for export
            def result = "";
            if( params.DownloadType != null )
            {
              gLogger.info '====================Dowmload Result==================='

              String downloadType = params.DownloadType
              String resultStream

              if(downloadType!=null){

                if( downloadType.equalsIgnoreCase("NodeAttribute")){
                   result = session.getAttribute("attributeList")
                   long totalConditions = Long.parseLong(session.getAttribute("totalConditions").toString());
                   resultStream = StatisticsAttributesUtil.getInstance().preapreNodeAttribute(result,totalConditions);
                }

                def fileName = params.fileName
                if(fileName == null ){
                  fileName = "default"
                }

                response.contentType = ConfigurationHolder.config.grails.mime.types[params.format]
                response.setHeader("Content-disposition", "attachment; filename=${fileName}.${params.extension}")
                response.outputStream << resultStream
                response.outputStream.flush()
              }
            }
      }
    }
}
